<!--  -->
<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">

      <el-row :gutter="20">

        <el-col :span="8">
          <div class="grid-content bg-purple">
            <!-- 搜索添加区域 -->
            <el-input placeholder="请输入内容"
                      v-model="userObj.query"
                      clearable
                      @clear="getUserList">
              <el-button slot="append"
                         icon="el-icon-search"
                         @click="getUserList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
                     @click="addDialogVisible = true">添加</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="users"
                border
                stripe
                style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username"
                         label="姓名"
                         width="180">
        </el-table-column>
        <el-table-column prop="email"
                         label="邮箱"
                         width="180">
        </el-table-column>
        <el-table-column prop="mobile"
                         label="电话">
        </el-table-column>
        <el-table-column prop="role_name"
                         label="角色"
                         width="180">
        </el-table-column>
        <el-table-column prop="mg_state"
                         label="状态"
                         width="180">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state"
                       active-color="blue"
                       @change="changeUserStatus(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="180">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="showDialogVisble(scope.row.id)"></el-button>
            <!-- 删除 -->
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="deleteUserById(scope.row.id)"></el-button>
            <!-- 分配角色 -->
            <el-tooltip class="item"
                        effect="dark"
                        content="分配角色"
                        placement="top"
                        :enterable="false">
              <el-button type="warning"
                         icon="el-icon-setting"
                         size="mini"
                         @click="SetRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器区域 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="userObj.pagenum"
                     :page-sizes="[1,2,5,10]"
                     :page-size="userObj.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog title="提示"
                 :visible.sync="addDialogVisible"
                 width="50%"
                 @close="addDialogClose">
        <!-- 内容主题区域 -->
        <el-form :model="addUserForm"
                 :rules="addUserFormRules"
                 ref="addUserFormRef"
                 label-width="100px">
          <el-form-item label="用户名称"
                        prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码"
                        prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱"
                        prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机"
                        prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="addDialogVisible = false ">取 消</el-button>
          <el-button type="primary"
                     @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框 -->
      <el-dialog title="提示"
                 :visible.sync="editDialogVisible"
                 width="50%"
                 @close="editDialogClosed">
        <el-form :model="editUserForm"
                 :rules="editUserFormRules"
                 ref="editUserFormRef"
                 label-width="100px">
          <el-form-item label="用户名称"
                        prop="username">
            <el-input v-model="editUserForm.username"
                      disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱"
                        prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机"
                        prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="editUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 控制分配权限的对话框 -->
      <el-dialog title="提示"
                 :visible.sync="SetRoleDialogVisible"
                 width="30%"
                 @close="SetRoleDialogClosed">
        <div>
          <p>当前的用户:{{userInfo.username}}</p>
          <p>当前的角色:{{userInfo.role_name}}</p>
          <p>
            角色列表:
            <el-select v-model="selectRoleId"
                       placeholder="请选择">
              <el-option v-for="item in rolesList"
                         :key="item.id"
                         :label="item.roleName"
                         :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="SetRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="saveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { reqAuthorizeRole, reqUserList, reqChangeUserStatus, reqGetusers, reqGetusersById, reqEditUsersById, reqDeleteUserById, reqGetRoles } from '@/api/index'
export default {
  data () {
    // 定义验证邮箱的自定义校验规则
    const checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const emailReg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
      if (emailReg.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 定义手机号的自定义校验规则
    const checkMobile = (rule, value, cb) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('手机号码格式不正确'))
      }
    }
    return {
      userObj: {
        query: '',
        // 当前第几页数据
        pagenum: 1,
        // 显示多少页
        pagesize: 2
      },
      // 接口返回数据总条数
      total: 0,
      // 用户数据集合
      users: [],
      // 控制对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户表单验证
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单验证规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2到 10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在 6到 15个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制修改用户对话框
      editDialogVisible: false,
      // 编辑用户信息
      editUserForm: {},
      // 修改用户表单的验证规则
      editUserFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色对话框的显示和隐藏
      SetRoleDialogVisible: false,
      // 需要被分配权限的角色信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色ID值
      selectRoleId: ''
    }
  },
  methods: {
    // 1.获取用户数据
    async getUserList () {
      const { data: res } = await reqUserList(this.userObj)
      if (res.meta.status != 200) return this.$message.error('获取用户列表失败')
      this.total = res.data.total
      this.users = res.data.users
    },
    // 2.监听pageSize改变事件
    handleSizeChange (newSize) {
      // console.log(newSize)
      // 2.1 新page
      this.userObj.pagesize = newSize
      // 2.2 发送请求
      this.getUserList()
    },
    // 3.页码值改变事件
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.userObj.pagenum = newPage
      this.getUserList()
    },
    // 4.修改用户状态
    async changeUserStatus (userinfo) {
      // console.log(userinfo)
      const { data: res } = await reqChangeUserStatus(userinfo.id, userinfo.mg_state)
      if (res.meta.status != 200) {
        // 修改失败的话，需要将switch状态改成原来的状态
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('修改用户状态失败')
      } else {
        return this.$message.success('修改用户状态成功')
      }
    },
    // 5.对话框的关闭事件
    addDialogClose () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 6.添加用户
    addUser () {
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('添加用户表单未通过')
        };
        // 校验通过,发送网络请求
        const { data: res } = await reqGetusers(this.addUserForm)
        if (res.meta.status != 201) return this.$message.error('添加用户失败')
        // 对话框隐藏
        this.addDialogVisible = false
        // 重新获取用户数据
        this.getUserList()
        return this.$message.success('添加用户成功')
      })
    },
    // 7.控制用户编辑的显示与隐藏
    async showDialogVisble (ID) {
      const { data: res } = await reqGetusersById(ID)
      // console.log(res)
      if (res.meta.status != 200) return this.$message.error('编辑用户信息失败')
      this.editUserForm = res.data
      this.editDialogVisible = true
    },
    // 8.监听修改用户表单用户编辑重置
    editDialogClosed () {
      this.$refs.editUserFormRef.resetFields()
    },
    // 9.修改用户信息
    editUser () {
      this.$refs.editUserFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await reqEditUsersById(this.editUserForm.id, { email: this.editUserForm.email, mobile: this.editUserForm.mobile })
          if (res.meta.status != 200) {
            return this.$message.error('修改用户信息失败')
          }
          // 将弹出窗口关闭
          this.editDialogVisible = false
          // 刷新数据
          this.getUserList()
          // 提示修改成功
          this.$message.success('用户信息修改成功')
        } else {
          return this.$message.error('修改用户表单没通过')
        }
      })
    },
    // 10.根据ID删除用户
    async deleteUserById (ID) {
      const result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((error) => {
        return error
      }
      )
      // result结果点击确定返回confirm字符串,点击取消返回cancel字符串
      if (result == 'cancel') {
        return this.$message.info('停止删除用户')
      }
      const { data: res } = await reqDeleteUserById(ID)
      if (res.meta.status != 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getUserList()
    },
    // 11.控制分配权限
    async SetRole (userInfo) {
      this.userInfo = userInfo
      // 11.1 获取所有角色的数据列表
      const { data: res } = await reqGetRoles('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      this.SetRoleDialogVisible = true
    },
    // 12.点击确定，分配角色
    async saveRoleInfo () {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配新的角色')
      }

      const { data: res } = await reqAuthorizeRole(this.userInfo.id, this.selectRoleId)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败')
      }
      this.$message.success('更新角色成功')
      this.getUserList()
      this.SetRoleDialogVisible = false
    },
    // 13.对话框关闭事件
    SetRoleDialogClosed () {
      this.selectRoleId = ''
      this.userInfo = {}
    }
  },
  // 生命周期 - 创建完成（访问当前this实例）
  created () {

  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted () {
    this.getUserList()
  }
}
</script>
<style lang="less" scoped>
.el-breadcrumb {
  margin: 0 0 20px;
  font-size: 12px;
}
.el-card {
  box-shadow: 0 0 0 rgba(0, 0, 0, 0.15) !important;
}
.el-table {
  margin-top: 20px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 20px;
}
</style>
